<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('联系人') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('姓名')" prop="contactsName">
        <el-input
          v-model="queryParams.contactsName"
          :placeholder="$t('姓名')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('所属公司')" prop="company">
        <el-input
          v-model="queryParams.company"
          :placeholder="$t('所属公司')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item v-if="!getBusinessId" :label="$t('业务类型')" prop="businessType">
        <dictSelect
          v-model="queryParams.businessType"
          :clearable="true"
          dictionary="main_body_type_all_crm"
          @input="emptyBusinessId"
        />
      </el-form-item>
      <el-form-item v-if="!getBusinessId" :label="$t('主体名称')" prop="businessId">
        <MainBodySelect
          v-model="queryParams.businessId"
          :parameters="queryParams.businessType"
          :placeholder="$t('请先选择业务类型')"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['contact:person:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['contact:person:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['contact:person:import']"
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >{{ $t('导入') }}
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" tooltip-effect="darkTable" :data="dealContactsList" border>
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <!--<el-table-column v-if="!this.$route.query.id" :label="业务类型" align="center" prop="businessType" />-->
      <!--<el-table-column v-if="!this.$route.query.id" :label="业务名称" align="center" prop="businessId" />-->
      <el-table-column :label="$t('姓名')" align="center" prop="contactsName" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" @click="updateHandle(scope.row)">{{ scope.row.contactsName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('联系电话')" align="center" prop="phone" show-overflow-tooltip />
      <el-table-column :label="$t('所属公司')" align="center" prop="company" show-overflow-tooltip />
      <el-table-column :label="$t('职位/角色')" align="center" prop="position" show-overflow-tooltip />
      <el-table-column :label="$t('电子邮箱')" align="center" prop="email" show-overflow-tooltip />
      <el-table-column :label="$t('邮箱发送方式')" align="center" prop="emailSendingType" show-overflow-tooltip :formatter="formatEmailSendType" />
      <el-table-column :label="$t('微信账户')" align="center" prop="weChat" show-overflow-tooltip />
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['contact:person:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['contact:person:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目联系人对话框 -->
    <el-dialog v-if="formOpen" :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <contactPersonForm ref="contactPersonForm" :bus-type="busType || dealData.busType" />
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport+ '&businessId=' + getBusinessId + '&businessType=' + formatBusType(busType) "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">{{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" class="el-icon-download el-icon--right" style="font-size:12px;float:left;" @click="fetchTemplate">
          {{ $t('下载模板') }}
        </el-button>
        <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDealContacts,
  delDealContacts,
  deleteByIds
} from '@/api/deal/contact/contactsPerson'
import contactPersonForm from './contactPersonForm.vue'
import MainBodySelect from '@/components/MainBodySelect/index'
import { getToken } from '@/utils/auth'
export default {
  components: {
    contactPersonForm,
    MainBodySelect
  },
  props: {
    busType: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 项目联系人表格数据
      dealContactsList: [],
      // 弹出层标题
      title: '联系人',
      // 是否显示弹出层
      formOpen: false,
      // 查询参数
      queryParams: {
        businessType: undefined,
        businessId: undefined,
        contactsName: undefined,
        company: undefined,
        pageNum: 1,
        pageSize: 10
      },
      emailSendingTypeOptions: [],
      // 业务id
      getBusinessId: this.$route.query.id ? this.$route.query.id : '',
      // 表单参数
      form: {},
      // 项目data
      dealData: '',
      // 表单校验
      rules: {
        contactsName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        phone: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        company: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        position: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        email: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 业务类型字典
      mainBodyTypeAllOptions: [],
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/contact/contactPerson/importData'
      }
    }
  },
  mounted() {
    this.getBusinessIdMethod()
    this.$bus.$emit('async_done')
  },
  created() {
    this.getList()
    this.getDicts('email_sending_type').then(response => {
      this.emailSendingTypeOptions = response.data
    })
    this.getDicts('main_body_type_all_crm').then(response => {
      this.mainBodyTypeAllOptions = response.data
    })
    // 根据url获取当前所在业务类型
    if (this.$route.fullPath) {
      var url = this.$route.fullPath
      if (url.includes('/lpBase')) {
        this.busType = 'lpInvestor'
      } else if (url.includes('/dealBase')) {
        this.busType = 'deal'
      } else if (url.includes('/gpBase')) {
        this.busType = 'managerAll'
      } else if (url.includes('/mediation')) {
        this.busType = 'mediation'
      }
      }
  },
  methods: {
    init(data) {
      this.dealData = data
    },
    /** 查询项目联系人列表 */
    getList() {
      this.loading = true
      if (this.getBusinessId) {
        this.getBusinessIdMethod()
      }
      listDealContacts(this.queryParams).then(response => {
        this.dealContactsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 翻译邮箱发送方式字典
    formatEmailSendType(row) {
      return this.selectDictLabel(this.emailSendingTypeOptions, row.emailSendingType)
    },
    // 翻译业务类型
    formatBusType(value) {
      return this.selectDictLabel(this.mainBodyTypeAllOptions, value)
    },
    getBusinessIdMethod() {
      if (this.getBusinessId === undefined || this.getBusinessId === '' || this.getBusinessId === null) {
        if (this.$route.path.includes('lpBase')) {
          this.getBusinessId = this.$route.query.lpId
        }
      }
      this.queryParams.businessId = this.getBusinessId
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: undefined,
        contactsName: undefined,
        phone: undefined,
        company: undefined,
        position: undefined,
        email: undefined,
        weChat: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      this.formOpen = true
      this.$nextTick(() => {
        this.$refs.contactPersonForm.init(null)
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.contactPersonForm.init(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('该主体下的联系人会同步删除，是否继续?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(function() {
          return delDealContacts(row.id)
        })
        .then(() => {
          this.getList()
          this.msgSuccess(this.$t('删除成功'))
        })
        .catch(function() {})
    },
    /** 导出按钮操作 */
    exportHandle() {
      this.downLoadExcel('/contact/contactPerson/export', this.queryParams)
    },
    // 导入
    handleImport() {
      this.upload.title = this.$t('导入')
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      if (!response.msg.toString().includes('以下姓名重复：')) {
        console.log(response, 'response.msg')
        this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
        this.getList()
      } else {
        // 姓名重复选择
        this.$confirm(response.msg, this.$t('有重复姓名是否继续导入?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          this.getList()
          this.msgSuccess(this.$t('成功导入' + response.data.length + '条数据'))
        }).catch(() => {
          if (response.data) {
            deleteByIds(response.data)
          }
          this.$message({
            type: 'info',
            message: '导入已取消'
          })
        })
      }
    },
    // 下载模板
    fetchTemplate() {
      const href1 = window.location.href
      const href2 = this.$route.path
      const url = href1.substring(0, href1.indexOf(href2))
      if (this.$route.query.id) {
        window.location.href = url + '/template/contactPersonInterImportTemplate.xlsx'
      } else {
        window.location.href = url + '/template/contactPersonImportTemplate.xlsx'
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 清空二级选项
    emptyBusinessId() {
      this.queryParams.businessId = null
    }
  }
}
</script>
